<?php

namespace app\common\controller;

use think\facade\Cache;
use think\facade\Config;

class WeChat
{
    /*
     * 生成带参数的小程序二维码
     **/
    public function getQRCode($uid)
    {
        // 获取access_token
        $token = $this->getAccessToken();
        $token = json_decode($token,true);
        $access_token = $token['access_token'];
        // 拼接微信服务端获取二维码需要的url
        $url = 'https://api.weixin.qq.com/wxa/getwxacode?access_token='.$access_token;
        $data['path'] = "pages/details/details?id=".$uid;
        $json = json_encode($data);
        $result = curl_post($url, $json);
        //保存到服务器
        $bh = time().rand(1000,9999);
        $filePath = './static/api/wxqrcode/' . $bh . '.png';
        $file = fopen($filePath, 'w');
        fwrite($file, $result);
        fclose($file);
        $codePath = substr($filePath,1);
        return $codePath;
    }

    /*
     * 生成带参数的小程序二维码(商品分享)
     **/
    public function getGoodsQRCode($id)
    {
        // 获取access_token
        $access_token = Cache::get('access_token');
        if (empty($access_token)) {
            $token = $this->getAccessToken();
            $token = json_decode($token,true);
            $access_token = $token['access_token'];
            Cache::set('access_token',$access_token,7000);
        }
        // 拼接微信服务端获取二维码需要的url
        $url = 'https://api.weixin.qq.com/wxa/getwxacode?access_token='.$access_token;
        $data['path'] = "pages/shop/goods_detail?id=".$id;
        $json = json_encode($data);
        $result = curl_post($url, $json);
        //保存到服务器
        $bh = time().rand(1000,9999);
        $filePath = './uploads/wxqrcode/' . $bh . '.png';
        $file = fopen($filePath, 'w');
        fwrite($file, $result);
        fclose($file);
        $codePath = substr($filePath,1);
        return $codePath;
    }

    /**
     * 获取access_token
     */
    public function getAccessToken()
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.config('config.wechat.appid').'&secret='.config('config.wechat.app_secret');
        $result = curl_get($url);
        return $result;
    }
}